package com.isatechindonesia.isatracker;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBClass extends SQLiteOpenHelper {

	private String now;

	public DBClass(Context context) {
		super(context, "db_tracker", null, 2);
				
		SimpleDateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd' 'HH:mm:ss");
		Date date = new Date();		
		now = dFormat.format(date);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		
		db.execSQL("CREATE TABLE if not exists tb_log "
				+ "(_id INTEGER PRIMARY KEY AUTOINCREMENT, " + "lat REAL, "
				+ "lon REAL, speed REAL, heading REAL, altitude REAL, accuracy REAL, date TEXT);");
				
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		
		db.execSQL("DROP TABLE IF EXISTS tb_info");
		db.execSQL("DROP TABLE IF EXISTS tb_log");
		onCreate(db);
	}
	
	public void insertLog(Logger log) {

		SQLiteDatabase db = this.getWritableDatabase();
		ContentValues values = new ContentValues();

		values.put("lat", log.getLat());
		values.put("lon", log.getLon());
		values.put("speed", log.getSpeed());
		values.put("heading", log.getHeading());
		values.put("altitude", log.getAltitude());
		values.put("accuracy", log.getAccuracy());
		values.put("date", now);

		db.insert("tb_log", null, values);
		db.close();

	}
	
	public List<Logger> getLog() {
		List<Logger> shoutList = new ArrayList<Logger>();

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cur = db.rawQuery(
				"Select _id,lat,lon,speed,heading,altitude,accuracy,date "
				+ "From tb_log Order By date Desc Limit 100", null);

		if (cur.moveToFirst()) {
			do {
				Logger log = new Logger();
				log.set_id(Integer.parseInt(cur.getString(cur
						.getColumnIndex("_id"))));
				log.setLat(Double.parseDouble(cur.getString(cur.getColumnIndex("lat"))));
				log.setLon(Double.parseDouble(cur.getString(cur.getColumnIndex("lon"))));
				log.setSpeed(Double.parseDouble(cur.getString(cur.getColumnIndex("speed"))));
				log.setHeading(Double.parseDouble(cur.getString(cur.getColumnIndex("heading"))));
				log.setAltitude(Double.parseDouble(cur.getString(cur.getColumnIndex("altitude"))));
				log.setAccuracy(Double.parseDouble(cur.getString(cur.getColumnIndex("accuracy"))));
				log.setDate(cur.getString(cur.getColumnIndex("date")));
				
				shoutList.add(log);
			} while (cur.moveToNext());
		}

		cur.close();
		db.close();

		return shoutList;
	}
	
	public void deleteLog(int id) {
		SQLiteDatabase db = this.getWritableDatabase();
		String str = "Delete From tb_log Where _id = "+id;

		db.execSQL(str);
	}
	
}
